package com.xsomnus.java_basic.juc.lock;

import java.util.concurrent.atomic.AtomicReference;

/**
 * @author @叶小夏
 * @since 2019/7/27 0027 16:33
 * - 才需学也,学需静也/非淡泊无以明志，非宁静无以致远
 *
 * http://ifeve.com/java_lock_see1/
 */
public class SpinLock {

    private AtomicReference<Thread> sign = new AtomicReference<>();

    static int count = 1;

    public void lock() {
        Thread current = Thread.currentThread();
        while (!sign.compareAndSet(null, current)) {
        }
    }


    public void unlock() {
        Thread current = Thread.currentThread();
        sign.compareAndSet(current, null);
    }

    static SpinLock lock = new SpinLock();


    static class TestTask extends Thread {

        String myname;

        public TestTask(String name) {
            this.myname = name;
        }

        @Override
        public void run() {
            lock.lock();
            try {
                count++;
                System.out.println(myname + " and val = " + count);
                Thread.sleep(5000);
            } catch (InterruptedException e) {
                e.printStackTrace();
            } finally {
                lock.unlock();
            }
        }
    }

    public static void main(String[] args) {
        for (int i = 0; i < 10; i++) {
            new TestTask(""+i).start();
        }
    }


}
